#! /usr/bin/env python
import opentick
import logging
from time    import sleep
from getpass import getpass

class ExchangeListClient( opentick.OTClient ):
    """OTClient subclass used to login to the OpenTick servers and obtain a list
    of exchanges.
    """
    def __init__( self ):
        super( ExchangeListClient, self ).__init__()
        #
        self.__mIsExchangeListReceived = False
        self.__mIsErrorEncountered     = False
        return 
        
    def IsExchangeListReceived( self ):
        return self.__mIsExchangeListReceived
        
    def IsErrorEncountered( self ):
        return self.__mIsErrorEncountered
        
    def onLogin( self ):
        logging.info( "Login successful." )
        logging.info( "Requesting list of exchanges. " )
        #
        # Request a list of exchanges that can be accessed by the current
        # user. The onListExchanges() method will be called when this is received
        # from the server. We ignore the request_id returned by this method
        # in this sample code.
        #
        request_id = self.requestListExchanges()
        return 
        
    def onListExchanges( self, 
                         exchangeList ):
        logging.info( "List of exchanges received." )
        #
        # Do nothing if the exchange list is empty.
        #
        if ( None == exchangeList ) or ( 0 == len( exchangeList ) ):
            logging.warning( "Empty exchange list received from OTFeed server." )

        #
        # Display a formatted list of exchanges. A lot of magic numbers are
        # used here to format the list. These are chosen fairly arbitrarily
        # and through trial and error. They have little or no effect on the
        # logic of the program.
        #            
        format_string = "%-5s %-60s %-5s"
        print format_string % ( 'Code', 'Title', 'Available?' )
        print '---------------------------------------------------------------------------'
        #
        for i in range(0, len(exchangeList) ):
            print format_string % ( exchangeList[i].getCode(), \
                  exchangeList[i].getTitle(), \
                  exchangeList[i].getAvailable() )
        
        self.__mIsExchangeListReceived = True 
        return
    
    def onError( self, otError ):
        logging.error( "[" + str(otError.getRequestId()) + ":" + str(otError.getCode() ) +
                       "] " + otError.getDescription() )
        self.__mIsErrorEncountered = True 
        return 
#
# Run the remaining lines if we are in the top-level script environment.
#
if __name__ == "__main__":
    logging.basicConfig( level  = logging.DEBUG,
                         format = '%(asctime)s %(levelname)s %(message)s' )
    #
    # Create an instance of our OpenTick client and add a server host.
    #
    client = ExchangeListClient()
    client.addHost( "feed2.opentick.com", 10010 )
    #
    # Ask the user for a login account name and password to connect to the 
    # OpenTick server.
    #
    username = raw_input( "Enter the user name: " )
    password = getpass( "Password for " + username + ": " )
    #
    # Initiate login process. 
    #
    client.login( username, password )
    #
    # Wait for the client to request and receive the exchange list.
    #
    while ( ( not client.IsExchangeListReceived() ) and
            ( not client.IsErrorEncountered() ) ):
        sleep( 1 )
    #
